<template>
  <div class="CostAdjust">
    <div class="CostAdjust-header">
      <div class="CostAdjust-header-left">
        <div class="CostAdjust-header-desc">
          选择商品后输入“调整成本”金额（对当前库存总价值的增减，可正可负，两位小数），系统计算新的平均成本
        </div>
      </div>
    </div>

    <!-- 表单区域 -->
    <div class="CostAdjust-form-wrapper">
      <el-form :model="form" label-width="110px" class="CostAdjust-form">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="商品" required>
              <div class="CostAdjust-inline-select">
                <el-input v-model="productDisplay" disabled placeholder="请选择商品"/>
                <el-button type="primary" @click="openSelectProduct">选择</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前库存(件)">
              <el-input v-model="inventoryInfo.balanceQuantity" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="当前均价(¥)">
              <el-input v-model="inventoryInfo.currentAvgCost" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调整成本(¥)" required>
              <el-input-number v-model="form.adjustCost" :step="1" :precision="2" :controls="true" :min="-9999999"
                               :max="9999999" placeholder="输入正负差值" class="CostAdjust-adjust-number"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.note" type="textarea" :rows="3" maxlength="200" show-word-limit
                        placeholder="说明调整原因"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 预览信息 -->
    <div class="CostAdjust-preview">
      <div class="CostAdjust-preview-row">
        <div class="CostAdjust-preview-label">新平均成本：</div>
        <div class="CostAdjust-preview-value">¥ {{ currentAvgCostAfterDisplay }}</div>
      </div>
      <div class="CostAdjust-preview-row">
        <div class="CostAdjust-preview-label">价值影响合计：</div>
        <div class="CostAdjust-preview-value" :class="{'is-negative': impactValue < 0, 'is-positive': impactValue > 0}">
          ¥ {{ impactValueDisplay }}
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="CostAdjust-actions">
      <el-button type="primary" :disabled="!canSubmit" @click="handleSubmit">提交调整</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <ProductSelectDialog v-model:visible="selectDialogVisible" @selected="handleProductSelected"/>
  </div>
</template>

<script setup>
import {ref, reactive, computed, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import ProductSelectDialog from '../../../components/ProductSelectDialog.vue'
import {getProduct} from '../../../api/productApi.js'
import {adjustCost as apiAdjustCost} from '../../../api/costApi.js'

// 选择商品弹窗与展示
const selectDialogVisible = ref(false)
const productDisplay = ref('')

// 库存与成本原始信息
const inventoryInfo = reactive({ productId: null, balanceQuantity: 0, currentAvgCost: 0 })

// 表单
const form = reactive({ adjustCost: 0, note: '' }) // adjustCost = 总价值调整额

// 产品详情（预留后续显示单位等）
const productInfo = reactive({ id: null, code: '', name: '', unit: '' })
const productLoading = ref(false)

const openSelectProduct = () => { selectDialogVisible.value = true }

const handleProductSelected = async (product) => {
  selectDialogVisible.value = false
  if (!product) return
  productLoading.value = true
  try {
    const detail = await getProduct(product.id)
    productInfo.id = detail.id
    productInfo.code = detail.code
    productInfo.name = detail.name
    productInfo.unit = detail.unit
    productDisplay.value = detail.name
    inventoryInfo.productId = detail.id
    inventoryInfo.balanceQuantity = Number(detail.balanceQuantity || 0)
    inventoryInfo.currentAvgCost = Number(detail.currentAvgCost || 0)
  } catch (e) {
    ElMessage.error('获取商品详情失败')
  } finally { productLoading.value = false }
}

// 四舍五入两位
const round2 = (n) => { const num = Number(n || 0); return Math.round(num * 100) / 100 }
watch(() => form.adjustCost, v => { form.adjustCost = round2(v) })

// 计算新平均成本（计算后称 currentAvgCostAfter，以提交 currentAvgCost 字段统一）
const currentAvgCostAfter = computed(() => {
  if (!inventoryInfo.productId) return 0
  const qty = Number(inventoryInfo.balanceQuantity || 0)
  if (qty <= 0) return 0
  const originalAvg = round2(inventoryInfo.currentAvgCost)
  const adjustCost = round2(form.adjustCost)
  const originalTotal = round2(originalAvg * qty)
  const newTotal = round2(originalTotal + adjustCost)
  if (newTotal < 0) return 0
  return round2(newTotal / qty)
})

// 价值影响 = 调整额
const impactValue = computed(() => inventoryInfo.productId ? round2(form.adjustCost) : 0)
const currentAvgCostAfterDisplay = computed(() => currentAvgCostAfter.value.toFixed(2))
const impactValueDisplay = computed(() => impactValue.value.toFixed(2))

// 可提交条件
const canSubmit = computed(() => !!inventoryInfo.productId && Number(inventoryInfo.balanceQuantity) > 0 && form.adjustCost !== '' && form.adjustCost !== null)

// 提交
const handleSubmit = () => {
  if (!canSubmit.value) return
  const qty = Number(inventoryInfo.balanceQuantity || 0)
  if (qty <= 0) return ElMessage.error('当前库存为0，无法调整')
  const adjustCost = round2(form.adjustCost)
  const originalAvgCost = round2(inventoryInfo.currentAvgCost)
  const originalTotal = round2(originalAvgCost * qty)
  const newTotal = round2(originalTotal + adjustCost)
  if (newTotal < 0) return ElMessage.error('调整后总价值不能为负')
  if (currentAvgCostAfter.value < 0) return ElMessage.error('新平均成本不能为负')

  ElMessageBox.confirm(
    `确认将平均成本调整为 ¥${currentAvgCostAfterDisplay.value} (总价值变化：¥${impactValueDisplay.value})?`,
    '确认调整', { type: 'warning' }
  ).then(async () => {
    const payload = {
      productId: inventoryInfo.productId,
      adjustCost,
      note: form.note,
      inventory: qty,
      originalAvgCost,
      currentAvgCost: currentAvgCostAfter.value,
      originalTotal,
      newTotal
    }
    await apiAdjustCost(payload).then((res) => {
      ElMessage.success('成本调整成功')
    })
  }).catch(() => {})
}

// 重置
const handleReset = (onlyProduct = false) => {
  productDisplay.value = ''
  productInfo.id = null
  productInfo.code = ''
  productInfo.name = ''
  productInfo.unit = ''
  inventoryInfo.productId = null
  inventoryInfo.balanceQuantity = 0
  inventoryInfo.currentAvgCost = 0
  if (!onlyProduct) {
    form.adjustCost = 0
    form.note = ''
  }
}
</script>

<style scoped lang="scss">
.CostAdjust {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 16px 0;

  &-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 0 0 16px;
    border-bottom: 1px solid #eee;

    &-left {
      display: flex;
      flex-direction: column;
      gap: 4px;
    }

    &-desc {
      font-size: 12px;
      color: #909399;
      line-height: 1.4;
      max-width: 640px;
    }
  }

  &-form-wrapper {
    padding: 16px 0;
  }

  &-form {
    width: 100%;
  }

  &-inline-select {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 100%;
  }

  &-adjust-number {
    width: 100%;
  }

  &-preview {
    padding: 8px 0 16px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;

    &-row {
      display: flex;
      gap: 8px;
      font-size: 14px;
      align-items: center;
    }

    &-label {
      color: #606266;
      width: 110px;
      text-align: right;
    }

    &-value {
      font-weight: 600;
      color: #303133;

      &.is-negative {
        color: #f56c6c;
      }

      &.is-positive {
        color: #67c23a;
      }
    }
  }

  &-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 0 0;
  }
}
</style>
